package org.ruanjj.net;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class IpTcpSendFileMain {
    //客户端发送一个文件给服务器，服务器端接收文件保存在本地
    @Test
    public void client() throws UnknownHostException {
        InetAddress inet = InetAddress.getLocalHost();
        int port = 8989;
        try(Socket socket = new Socket(inet,port);
            OutputStream outputStream = socket.getOutputStream();
            InputStream inputStream = socket.getInputStream();
            FileInputStream fi = new FileInputStream("p1.jpeg")){

            outputStream.write(fi.readAllBytes());
            socket.shutdownOutput();

            String txt = new String(inputStream.readAllBytes());
            System.out.println(txt);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        System.out.println("客户端文件传输完成");
    }

    @Test
    public void server(){
        int port = 8989;
         try(
                 ServerSocket serverSocket = new ServerSocket(port);
                 Socket socket = serverSocket.accept();
                 InputStream inputStream = socket.getInputStream();
                 OutputStream outputStream = socket.getOutputStream();
                 FileOutputStream fi = new FileOutputStream("picture.jpeg")
            ){
             fi.write(inputStream.readAllBytes());
             outputStream.write("照片收到了，很漂亮".getBytes());
         } catch (IOException e) {
             throw new RuntimeException(e);
         }

        System.out.println("服务器端接收文件完毕");
    }
}
